import { Ref, onMounted } from 'vue'

interface UseIntersectionObserver {
  stop: () => void
}

/** 监听元素进入视口 */
export function useIntersectionObserver(
  target: Ref<Element>,
  cb: (isIntersecting: boolean, target: Element) => void
): UseIntersectionObserver {
  /** 创建视口与目标元素交叉监听器 */
  const intersectionObserver = new IntersectionObserver(
    (entries) => {
      /**
       * 如果被观察元素进入了视口则为true，否则为false
       */
      const isIntersecting = entries[0].isIntersecting
      /** 执行回调函数 */
      cb(isIntersecting, entries[0].target)
    },

    {
      threshold: 0.1
    }
  )
  /** 确保dom在页面中挂载完毕时对目标元素进行监听 */
  onMounted(() => {
    intersectionObserver.observe(target.value)
  })

  /**
   * 停止监听
   */

  function stop(): void {
    intersectionObserver.unobserve(target.value)
  }

  return {
    stop
  }
}
